package com.guoxue.action.front;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.guoxue.domain.LevelConfigVo;
import com.guoxue.domain.PlayerProgressVo;
import com.guoxue.domain.TapesRecordsVo;
import com.guoxue.domain.TapesShareVo;
import com.guoxue.domain.TotalInfoVo;
import com.guoxue.domain.UserVo;
import com.guoxue.service.ILevelConfigService;
import com.guoxue.service.IPlayerProgressService;
import com.guoxue.service.ITapesRecordsService;
import com.guoxue.service.ITapesShareService;
import com.guoxue.service.ITotalInfoService;
import com.guoxue.service.IUserService;
import com.guoxue.util.JsonUtil;
import com.guoxue.util.LoggerUtil;
import com.guoxue.util.MessageSendUtil;
import com.guoxue.util.OtherUtils;
import com.guoxue.util.PasswordUtil;

@Controller
@RequestMapping("User")
/**
 * 用户信息处理接口
 * 
 * @author young
 */
public class UserAction extends BaseAction {

	@Resource
	private IUserService userService;
	@Resource
	private ITapesRecordsService tapesService;
	@Resource
	private ITapesShareService shareService;
	@Resource
	private ITotalInfoService totalInfoService;
	@Resource
	private ILevelConfigService levelConfigService;
	@Resource
	private IPlayerProgressService playerProgressService;

	/**
	 * 
	 * @param req
	 * @param resp
	 * @param account(必)登录账号，快速登录时为手机唯一识别码
	 * @param password用户键入密码
	 * @param type(必)1:手机号登录。2、QQ登录.
	 *            3、微信登录.4、sina登录.5、快速登录.
	 */
	@RequestMapping(value = "/login")
	@ResponseBody
	public JSON login(HttpServletRequest req, HttpServletResponse resp, String account, String password, Integer type) {
		try {
			if (isEmpty(account) || type == null) {
				return Message(ERROR, BAD_PARAM, null);
			} else {
				UserVo user = new UserVo();
				if (type == 2 || type == 3 || type == 4 || type == 5) { // 非手机账号登录
					user = userService.getUser(account);
					if (user != null && user.getStatus() != 3) {
						if (user.getNickName() == null || user.getSex() <= 0) {
							return Message(INFO_NOT_COMPLETE, "账号信息未完善", account); // 账号信息未完善，提示跳转创建角色
						} else if (user.getStatus() == 3) {
							return Message(ERROR, "账号不正常", account);
						} else {
							req.getSession().setAttribute("user", user);
							return Message(SUCCESS, "登录成功", user.getId());
						}
					} else {
						UserVo entiy = new UserVo();
						entiy.setCreatedAt(new Date().toString());
						entiy.setStatus(1);
						if (type == 2) { // QQ用户
							entiy.setQqAccount(account);
						} else if (type == 3) { // 微信用户
							entiy.setWechatAccount(account);
						} else if (type == 4) { // sina用户
							entiy.setSinaAccount(account);
						} else {
							entiy.setIdentityId(account);
							entiy.setStatus(2);
						}
						userService.saveUser(entiy);
						return Message(INFO_NOT_COMPLETE, "账号信息未完善", account);
					}
				} else if (type == 1) { // 手机登录
					if ("".equals(password) || password == null) {
						return Message(ERROR, BAD_PARAM, null);
					}
					user = userService.getUserByTel(account);
					if (user != null) {
						JSONObject obj = new JSONObject();
						obj.put("uid", user.getId());
						if (PasswordUtil.validPassword(user.getUserPassword(), password, user.getSalt())) {
							if (user.getNickName() == null || user.getSex() <= 0) {
								return Message(INFO_NOT_COMPLETE, "账号信息未完善", obj);
							}
							req.getSession().setAttribute("user", user);
							return Message(SUCCESS, "登录成功", obj);
						} else if (user.getStatus() == 3) {
							return Message(ERROR, "账号不正常", obj);
						} else {
							return Message(ERROR, PASSWORD_ERROR, obj);
						}
					} else {
						return Message(ERROR, NOT_EXIST, account);
					}
				} else {
					return Message(ERROR, "未知登录类型", null);
				}
			}
		} catch (Exception e) {
			return LoggerUtil.logInfo(e, ERROR);
		}
	}

	/**
	 * 创建社交账号以及游客注册新用户。
	 * 
	 * @param req
	 * @param resp
	 * @param account
	 *            账号参数
	 * @param identityId(必)手机唯一识别码
	 * @param type
	 *            1、QQ用户. 2、微信用户.3、sina用户.4、快速登录.
	 *//*
		 * @RequestMapping(value = "/createUserByAccount")
		 * 
		 * @ResponseBody public JSON creatUserByAccount(HttpServletRequest req,
		 * HttpServletResponse resp, String account, String identityId, Integer
		 * type) { try { if (type == null) { return Message(ERROR,
		 * BAD_PARAM,null); // 提示参数不全 } else { User user = new User();
		 * user.setIdentityId(identityId); user.setStatus(1); if (type == 5) {
		 * User entityA = userService.getUser(identityId); if (entityA != null)
		 * { // 当前手机游客身份存在 req.getSession().setAttribute("user", entityA);
		 * return Message(ALREADY_REG, GO_LOGIN,identityId); } else {
		 * user.setStatus(2); } } else { User entityB =
		 * userService.getUser(account); // 判断当前用户是否已存在，直接跳转登录？ if (entityB !=
		 * null) { req.getSession().setAttribute("user", entityB); return
		 * Message(ALREADY_REG, GO_LOGIN,account); } else { if (type == 2 &&
		 * !("".equals(account)) && account != null) { // QQ用户
		 * user.setQqAccount(account); } else if (type == 3 &&
		 * !("".equals(account)) && account != null) { // 微信用户
		 * user.setWechatAccount(account); } else if (type == 4 &&
		 * !("".equals(account)) && account != null) { // sina用户
		 * user.setSinaAccount(account); } else { return Message(ERROR,
		 * BAD_PARAM,null); } } } user.setCreatedAt(new Date());
		 * userService.saveUser(user); req.getSession().setAttribute("user",
		 * user); return Message(SUCCESS, "注册成功",
		 * account==null||"".equals(account)?identityId:account); } } catch
		 * (Exception e) { return LoggerUtil.logInfo(e, ERROR); }
		 * 
		 * }
		 */

	/**
	 * 创建手机账号注册新用户
	 * 
	 * @param req
	 * @param resp
	 * @param tel(必)用户绑定电话
	 * @param pass(必)用户键入密码
	 * @param messageCode(必)短信验证码
	 */
	@RequestMapping("/createUserByTel")
	@ResponseBody
	public JSON creatUserByTel(HttpServletRequest req, HttpServletResponse resp, String tel, String pass,
			String messageCode) {
		try {
			if (isEmpty(tel) || isEmpty(pass) || isEmpty(messageCode)) {
				return Message(ERROR, BAD_PARAM, null);
			} else {
				UserVo entity = userService.getUserByTel(tel); // 判断当前号码是否已被绑定
				if (entity != null) {
					req.getSession().setAttribute("user", entity);
					return Message(ALREADY_REG, GO_LOGIN, tel);
				} else {
					String checkCode = (String) req.getSession().getAttribute("message");
					if (OUT_OF_DATE.equals(checkCode) || isEmpty(checkCode)) {
						return Message(ERROR, "验证码失效", "");
					} else {
						if (!messageCode.equals(checkCode)) { // 短信验证码验证
							return Message(ERROR, VERIFICATION_CODE_ERROR, null);
						} else {
							UserVo user = new UserVo();
							user.setUserPassword(pass);
							user = PasswordUtil.passwordGenerator(user); // 密码加密
							user.setUserTel(tel);
							user.setCreatedAt(OtherUtils.getCurrentDate());
							user.setStatus(1);
							userService.saveUser(user);
							req.getSession().setAttribute("message", OUT_OF_DATE);
							return Message(SUCCESS, "创建账号成功", user.getId());
						}
					}
				}
			}
		} catch (Exception e) {
			return LoggerUtil.logInfo(e, ERROR);
		}
	}

	/**
	 * 修改用户昵称
	 * 
	 * @param req
	 * @param resp
	 * @param nickName(必)提交的用户昵称
	 * @param account(必)任何一种绑定方式下的账号
	 * @return
	 */
	@RequestMapping("/createUserName")
	@ResponseBody
	public JSON creatUserName(HttpServletRequest req, HttpServletResponse resp, String nickName, String account,
			Integer sex) {
		try {
			if (isEmpty(nickName) || isEmpty(account) || sex == null) {
				return Message(ERROR, BAD_PARAM, null);
			} else {
				UserVo user = null;
				user = userService.getUserByNickname(nickName); // 验证用户名是否已存在
				if (user != null) {
					return Message(ERROR, "用户名已存在", nickName);
				} else {
					UserVo entiy = new UserVo();
					entiy = userService.getUser(account);
					if (entiy == null) {
						return Message(ERROR, "该账号未绑定", account); // 查看该账号是否有绑定用户
					} else {
						entiy.setNickName(nickName);
						entiy.setSex(sex);
						userService.saveUser(entiy);
						; // 通过之前绑定账号进行姓名修改
						req.getSession().setAttribute("user", entiy);
						return Message(SUCCESS, "添加昵称成功", account);
					}
				}
			}
		} catch (Exception e) {
			return LoggerUtil.logInfo(e, ERROR);
		}
	}

	/**
	 * 短信发送接口
	 * 
	 * @param req
	 * @param resp
	 * @param tel
	 * @param type
	 * @return
	 */
	@RequestMapping("/sendMessage")
	@ResponseBody
	public JSON sendMessage(HttpServletRequest req, HttpServletResponse resp, String tel, Integer type) {
		try {
			if (type != null) {
				if (type == 1) {
					UserVo entity = userService.getUserByTel(tel);// 检测当前手机号是否已注册
					if (entity == null) {
						if (!isEmpty(tel)) {
							String checkCode = MessageSendUtil.sendMessage(tel, "reg");
							if (checkCode.equals("400")) {
								return Message(ERROR, "获取验证码失败", null);
							} else {
								req.getSession().setAttribute("message", checkCode);
								return Message(SUCCESS, "验证码10分钟内有效", null);
							}
						} else {
							return Message(ERROR, BAD_PARAM, null);
						}
					} else {
						return Message(ALREADY_REG, GO_LOGIN, tel);
					}
				} else if (type == 2) {
					UserVo entityB = userService.getUserByTel(tel); // 检测当前手机号是否已注册
					if (entityB != null) {
						String checkCode = MessageSendUtil.sendMessage(tel, "modify");
						if (checkCode.equals("400")) {
							return Message(ERROR, "获取验证码失败", null);
						} else {
							req.getSession().setAttribute("modifyCode", checkCode);
							JSONObject obj = new JSONObject();
							obj.put("headUrl", entityB.getImgUrl());
							obj.put("messageCode", checkCode);
							return Message(SUCCESS, "验证码10分钟内有效", obj);
						}
					} else {
						return Message(ERROR, "当前账号未注册", tel);
					}
				} else {
					return Message(ERROR, "未知type类型", type);
				}
			} else {
				return Message(ERROR, BAD_PARAM, null);
			}
		} catch (Exception e) {
			return LoggerUtil.logInfo(e, ERROR);
		}
	}

	/**
	 * 密码修改
	 * 
	 * @param req
	 * @param resp
	 * @param tel
	 * @param modifyCode
	 * @param password
	 * @return
	 */
	@RequestMapping("/modifyPassword")
	@ResponseBody
	public JSON modifypassword(HttpServletRequest req, HttpServletResponse resp, String tel, String modifyCode,
			String password) {
		try {
			if (isEmpty(modifyCode) || isEmpty(tel) || isEmpty(password)) {
				return Message(ERROR, BAD_PARAM, null);
			} else {
				String checkCode = (String) req.getSession().getAttribute("modifyCode"); // 获取到系统存放验证码
				if (OUT_OF_DATE.equals(checkCode) || isEmpty(checkCode)) {
					return Message(ERROR, "验证码失效", null);
				} else {
					if (!checkCode.equals(modifyCode)) {
						return Message(ERROR, "验证码错误", null);
					} else {
						UserVo user = userService.getUserByTel(tel);
						if (user != null) {
							user.setUserPassword(password);
							user = PasswordUtil.passwordGenerator(user);
							userService.saveUser(user);
							req.getSession().setAttribute("modifyCode", OUT_OF_DATE);
							return Message(SUCCESS, "修改成功", null);
						} else {
							return Message(ERROR, "当前用户不存在", null);
						}
					}
				}
			}
		} catch (Exception e) {
			return LoggerUtil.logInfo(e, "密码修改失败");
		}
	}

	/**
	 * 后台管理禁用和启用用户
	 *  @param 用户id
	 * 
	 * */
	@RequestMapping("/del/member")
	@ResponseBody
	public JSON changeUserStatus(HttpServletRequest req, HttpServletResponse resp, Integer id) {
		try {
			userService.updateAccountStatus(id, 3);
			return Message(SUCCESS, "封号成功", null);
		} catch (Exception e) {
			return LoggerUtil.logInfo(e, "封号失败");
		}
	}

	/**
	 * 解锁账号
	 * 
	 * @param req
	 * @param resp
	 * @param id
	 * @return
	 */
	@RequestMapping("unblock/member")
	@ResponseBody
	public JSON unblocking(HttpServletRequest req, HttpServletResponse resp, Integer id) {
		try {
			userService.updateAccountStatus(id, 1);
			return Message(SUCCESS, "解除封号成功", null);
		} catch (Exception e) {
			return LoggerUtil.logInfo(e, "解除封号失败");
		}
	}

	/**
	 * 获取个人页面信息
	 * 
	 * @param req
	 * @param resp
	 * @param uid
	 * @return
	 */
	@RequestMapping("/getUserInfo")
	@ResponseBody
	public JSON getUserInfo(HttpServletRequest req, HttpServletResponse resp, Integer uid) {
		JSONObject obj = new JSONObject();
		if (uid == null) {
			return Message(ERROR, "未提交用户id", null);
		} else {
			UserVo user = userService.getUserByKey(uid);
			if (user == null) {
				return Message(ERROR, NOT_EXIST, null);
			} else {
				TotalInfoVo total = totalInfoService.getInfoByUid(user.getId());
				if (total == null) {
					total = new TotalInfoVo();
					total.setUid(user.getId());
					obj.put("follow", 0);
					obj.put("follower", 0);
					obj.put("listened", 0);
					totalInfoService.saveOrUpateInfo(total);
				} else {
					obj.put("follow", total.getFollow());
					obj.put("follower", total.getBeFollowed());
					obj.put("listened", total.getListened());
				}
				PlayerProgressVo player = playerProgressService.getPlayerProgressByUid(user.getId());// 获取当前用户等级进度信息
				int exp = 0;
				if (player == null) {
					player = new PlayerProgressVo();
					player.setUid(user.getId());
				} else {
					exp = player.getExp();
				}
				LevelConfigVo level = levelConfigService.getLevelByExp(exp);// 获取当前等级
				LevelConfigVo nextlevel = levelConfigService.getNextLevelByExp(exp);// 获取对应下一级所需经验
				obj.put("headUrl", user.getImgUrl());
				// TODO:关于国学吧账号问题
				obj.put("userId", "by201698754");
				obj.put("exp", exp);
				obj.put("nextLevelExp", nextlevel.getExp());
				obj.put("level", level.getLevel());
				// 获取用户上传录音信息
				List<TapesRecordsVo> tapes = tapesService.findByUidAndStatus(user.getId(), 0);
				if (tapes.size() == 0) {// 若没有返回null
					obj.put("tapes", null);
					return Message(SUCCESS, "获取用户信息成功", obj);
				} else {
					JSONArray tapesArray = new JSONArray();
					for (TapesRecordsVo t : tapes) {// 获取对应录音点击量等数据
						JSONObject tapesInfo = new JSONObject();
						TapesShareVo share = shareService.getTapesShareByTid(t.getId(), 0);
						tapesInfo.put("tapeId", t.getId());
						tapesInfo.put("size", t.getSize());
						tapesInfo.put("tapesName", t.getTapes());
						tapesInfo.put("commitTime", t.getCommitTime());
						tapesInfo.put("chapterId", t.getFlag());
						tapesInfo.put("chapterName", t.getChapter());
						if (share != null) {
							tapesInfo.put("commentCount", share.getCommentCount());
							tapesInfo.put("gifts", share.getGifts());
							tapesInfo.put("listened", share.getListened());
							tapesInfo.put("shareCount", share.getShareCount());
						} else {// 若未查询到对应记录则生成一条对应记录存放数据库
							tapesInfo.put("commentCount", 0);
							tapesInfo.put("gifts", 0);
							tapesInfo.put("listened", 0);
							tapesInfo.put("shareCount", 0);
							share = new TapesShareVo();
							share.setTapesId(t.getId());
							shareService.saveTapesShare(share);
						}
						tapesArray.add(tapesInfo);
					}
					obj.put("tapes", tapesArray);
					return Message(SUCCESS, "获取用户信息成功", obj);
				}
			}
		}
	}

	
	/**
	 * 删除录音
	 * @param req
	 * @param resp
	 * @param tapesId
	 * @return
	 */
	@RequestMapping("/delUserTapes")
	@ResponseBody
	public JSON delUserTapes(HttpServletRequest req, HttpServletResponse resp, Integer tapesId) {
		try {
			if (tapesId == null) {
				return Message(ERROR, "未提交录音文件id", null);
			} else {
				TapesRecordsVo t = tapesService.getTapesById(tapesId);
				if (t == null) {
					return Message(ERROR, "不存在该记录", null);
				} else {
					t.setSysflag(1);
					t.setDeleteTime(OtherUtils.getCurrentDate());
					tapesService.saveTapesRecords(t);
					return Message(SUCCESS, "删除成功", null);
				}
			}
		} catch (Exception e) {
			LoggerUtil.logInfo(e, "删除异常");
		}
		return null;
	}

}
